package model

import (
	"strconv"
	"strings"
)

type IntSplitStr string

func (iss IntSplitStr) Unmarshal() []int {
	ss := strings.Split(string(iss), ",")
	values := make([]int, 0)
	for _, s := range ss {
		if strings.TrimSpace(s) != "" {
			v, err := strconv.ParseInt(s, 10, 64)
			if err == nil {
				values = append(values, int(v))
			}
		}
	}
	return values
}

func (iss IntSplitStr) Marshal(values []int) IntSplitStr {
	ss := make([]string, 0)
	for _, i := range values {
		s := strings.TrimSpace(strconv.FormatInt(int64(i), 10))
		if s != "" {
			ss = append(ss, s)
		}
	}
	if len(ss) <= 0 {
		return ""
	}
	return IntSplitStr(strings.Join(ss, ","))
}

func (iss IntSplitStr) Add(value int) IntSplitStr {
	values := iss.Unmarshal()
	for _, v := range values {
		if v == value {
			return iss
		}
	}
	values = append(values, value)
	return iss.Marshal(values)
}

func (iss IntSplitStr) Delete(value int) IntSplitStr {
	values := iss.Unmarshal()
	newValues := make([]int, 0)
	for _, v := range values {
		if v != value {
			newValues = append(newValues, v)
		}
	}
	return iss.Marshal(newValues)
}
